﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.App.DTO;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Traceability
{
    /// <summary>
    /// 
    /// </summary>
    public class TraceabilityQueryCommandHandler : IRequestHandler<TraceabilityQueryCommand, APIResult<APIPaging<TraceabilityListDto>>>
    {
        private readonly IBaseRepository<T_Traceability> tranceRepository;
        private readonly IBaseRepository<T_Goods> goodsRepository;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tranceRepository"></param>
        /// <param name="goodsRepository"></param>
        public TraceabilityQueryCommandHandler(IBaseRepository<T_Traceability> tranceRepository, IBaseRepository<T_Goods> goodsRepository)
        {
            this.tranceRepository = tranceRepository;
            this.goodsRepository = goodsRepository;
        }

        public Task<APIResult<APIPaging<TraceabilityListDto>>> Handle(TraceabilityQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<TraceabilityListDto>> result = new APIResult<APIPaging<TraceabilityListDto>>();
            result.Code = APIEnum.ok;
            result.Message = "获取成功";
            var list = from a in tranceRepository.GetAll().AsNoTracking()
                       join b in goodsRepository.GetAll().AsNoTracking()
                       on a.SID equals b.ID
                       select new TraceabilityListDto
                       {
                           ID = a.ID,
                           SID = a.SID,
                           GoodsName = b.GoodsName,
                           Batch = a.Batch,
                           ShelfLife = a.ShelfLife,
                           LicenseNumber = a.LicenseNumber,
                           Manufacturers = a.Manufacturers,
                           CoverImageUrl = a.CoverImageUrl,
                           Perfection = a.Perfection,
                       };
            if (!string.IsNullOrEmpty(request.Batch))
            {
                list = list.Where(x => x.Batch == request.Batch);
            }
            if (request.Sid != null)
            {
                list = list.Where(x => x.SID == request.Sid);
            }
            APIPaging<TraceabilityListDto> paging = new APIPaging<TraceabilityListDto>();
            paging.RecordCount = list.Count();
            paging.List = list.OrderByDescending(x => x.ID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
